﻿using System;
using System.IO;
using System.Windows;
using MagicKey.Interfaces;
using MagicKey.Components.Database;

namespace MagicKey.Components.FileAccess
{
    public class FileAccess : IFileAccess
    {
        readonly static MagicDatabase Database = new MagicDatabase();
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool LoadFile(string path)
        {
            bool loadSuccessfull = false;

            try
            {
                var ftpHelper = new FtpHelper();
                var file = ftpHelper.DownloadFile(path);

                try
                {
                    if (file != null)
                        loadSuccessfull = true;
                }
                catch (Exception e)
                {
                    var msg = "Opening the file failed:\r\n " + path + " ! \r\n " + e.Message;
                    MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            //}
            return loadSuccessfull;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <param name="ownerId">The id of the owner</param>
        /// <returns>fullpath on the server</returns>
        public string UploadFile(string path, int ownerId)
        {
            var file = new FileInfo(path);
            var ftpHelper = new FtpHelper();

            string pathOnServer = ftpHelper.SetUri(file.Name);

            if (ftpHelper.UploadFile(file))
            {
                return pathOnServer;
            }

            const string msg = "Please check if the file does not already exist on the server.";
            MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            return string.Empty;
        }

        public bool Exists(string uri)
        {
            return File.Exists(uri);
        }

        /// <summary>
        /// </summary>
        /// <param name="path"></param>
        /// <param name="ownerId"></param>
        /// <returns></returns>
        public bool DeleteFile(string path, int ownerId)
        {
            if (Database.DeleteFile(path, ownerId))
            {
                var ftpHelper = new FtpHelper();
                if (ftpHelper.DeleteFile(new Uri(path)))
                    return true;
            }
            return false;
        }
    }
}